import os
import time

from appium import webdriver
from appium.options.android import UiAutomator2Options
from selenium.webdriver.ie.webdriver import WebDriver

from config import AppPackage, AppPath, MobileDevices


class DriverUtils:
    __driver = None
    # 创建驱动对象
    def get_driver(self,des_caps=MobileDevices):
        option = UiAutomator2Options().load_capabilities(des_caps)
        if self.__driver is None:
            self.__driver =  webdriver.Remote("http://127.0.0.1:4723/wd/hub", options=option)
        self.__driver.implicitly_wait(10)
        return self.__driver

    # 关闭驱动
    def quit_driver(self):
        time.sleep(5)
        if self.__driver:
            self.__driver.quit()
            self.__driver = None

    # 在 install_uninstall_app 方法中添加路径检查
    def install_uninstall_app(self, package=AppPackage, app_path=fr"{AppPath}\apkSoftware\tpshopAPP.apk"):
        # 检查文件是否存在
        if not os.path.exists(app_path):
            raise FileNotFoundError(f"APK文件不存在: {app_path}")

        # 如果存在就卸载了再安装
        if self.__driver.is_app_installed(package):
            self.__driver.remove_app(package)
            self.__driver.install_app(app_path)
        else:
            self.__driver.install_app(app_path)

if __name__ == '__main__':
    driver_utils = DriverUtils()
    driver_utils.get_driver()
    time.sleep(5)
    driver_utils.quit_driver()

    # driver_utils.install_uninstall_app()
